<?php namespace Phpcmf\Model;

class Member extends \Phpcmf\Model
{
    
    /**
     * 由用户名获取uid
     */
    function uid($name) {
        if ($name == $this->member['username']) {
            return $this->member['uid'];
        }
        $data = $this->db->table('member')->select('id')->where('username', dr_safe_replace($name))->get()->getRowArray();
        return intval($data['id']);
    }
    
    /**
     * 由uid获取用户名
     */
    function username($uid) {
        if ($uid == $this->member['uid']) {
            return $this->member['username'];
        }
        $data = $this->db->table('member')->select('username')->where('id', intval($uid))->get()->getRowArray();
        return $data['username'];
    }

    /**
     * 由uid获取电话
     */
    function phone($uid) {
        if ($uid == $this->member['uid']) {
            return $this->member['phone'];
        }
        $data = $this->db->table('member')->select('phone')->where('id', intval($uid))->get()->getRowArray();
        return $data['phone'];
    }

    // 用户基本信息
    function member_info($uid) {

        if ($uid == $this->member['uid']) {
            return $this->member;
        }

        $data = $this->db->table('member')->where('id', intval($uid))->get()->getRowArray();
        $data['uid'] = $data['id'];

        return $data;
    }

    /**
     * 登录记录
     *
     * @param	intval	$data		会员
     * @param	string	$OAuth		登录方式
     */
    private function _login_log($data, $type = '') {



    }

    /**
     * 取会员COOKIE
     */
    public function member_uid() {

        // 获取本地cookie
        $uid = (int)\Phpcmf\Service::L('Input')->get_cookie('member_uid');
        if (!$uid) {
            return 0;
        }

        return $uid;
    }


    /**
     * 初始化处理
     */
    public function init_member($member) {


    }

    /**
     * 验证会员有效性 1表示通过 0表示不通过
     */
    public function check_member_cookie($member) {

        // 获取本地认证cookie
        $cookie = \Phpcmf\Service::L('Input')->get_cookie('member_cookie');

        // 授权登陆时不验证
        if ($member['id'] && \Phpcmf\Service::C()->session()->get('member_auth_uid') == $member['id']) {
            return 1;
        } elseif (!$cookie) {
            return 0;
        } elseif (substr(md5(SYS_KEY.$member['password']), 5, 20) !== $cookie) {
            if (defined('UCSSO_API')) {
                $rt = ucsso_get_password($member['id']);
                if ($rt['code']) {
                    // 变更本地库
                    $this->db->table('member')->where('id', $member['id'])->update(array(
                        'salt' => $rt['data']['salt'],
                        'password' => $rt['data']['password'],
                    ));
                    return 1;
                }
            }
            return 0;
        }

        return 1;
    }

    /**
     * 授权登录信息
     */
    public function oauth($uid) {


    }

    /**
     * 会员信息
     */
    public function get_member($uid = 0, $name = '') {

        $uid = intval($uid);

        if ($uid) {
            $data = $this->db->table('member')->where('id', $uid)->get()->getRowArray();
        } elseif ($name) {
            $data = $this->db->table('member')->where('username', $name)->get()->getRowArray();
            $uid = (int)$data['id'];
        }
        if (!$data) {
            return null;
        }

        // 附表字段
        $data2 = $this->db->table('member_data')->where('id', $uid)->get()->getRowArray();
        $data2 && $data = $data + $data2;
        
        $data['uid'] = $data['id'];
        $data['authid'] = [];
        $data['avatar'] = dr_avatar($data['id']);
        $data['adminid'] = (int)$data['is_admin'];
        $data['tableid'] = (int)substr((string)$data['id'], -1, 1);


        $data['groupid'] = [];

        return $data;
    }

    // 获取authid
    public function authid($uid) {


        return [0];
    }
    
    // 更新用户组
    // member 用户信息
    // groups 拥有的用户组
    public function update_group($member, $groups) {


    }
    
    // 新增用户组
    public function insert_group($uid, $gid) {

    }
    
    // 手动变更等级
    public function update_level($uid, $gid, $lid) {

    }

    /**
     * 添加一条通知
     *
     * @param	string	$uid
     * @param	string	$note
     * @return	null
     */
    public function notice($uid, $type, $note, $url = '') {


    }

    /**
     * 系统提醒
     *
     * @param	site    站点id,公共部分0
     * @param	type    system系统  content内容相关  member会员相关 app应用相关 pay 交易相关
     * @param	msg     提醒内容
     * @param	uri     后台对应的链接
     * @param	to      通知对象 留空表示全部对象
     * array(
     *      to_uid 指定人
     *      to_rid 指定角色组
     * )
     */
    public function admin_notice($site, $type, $member, $msg, $uri, $to = []) {

        $this->db->table('admin_notice')->insert([
            'site' => (int)$site,
            'type' => $type,
            'msg' => $msg,
            'uri' => $uri,
            'to_rid' => intval($to['to_rid']),
            'to_uid' => intval($to['to_uid']),
            'status' => 0,
            'uid' => (int)$member['id'],
            'username' => $member['username'] ? $member['username'] : '',
            'op_uid' => 0,
            'op_username' => '',
            'updatetime' => 0,
            'inputtime' => SYS_TIME,
        ]);
    }
    
    // 执行提醒
    public function todo_admin_notice($uri, $site = 0) {
        $this->db->table('admin_notice')->where('site', (int)$site)->where('uri', $uri)->update([
            'status' => 3,
            'updatetime' => SYS_TIME,
        ]);
    }

    // 执行删除提醒
    public function delete_admin_notice($uri, $site = 0) {
        $this->db->table('admin_notice')->where('site', (int)$site)->where('uri', $uri)->delete();
    }
    

    // 审核用户
    public function verify_member($uid) {

    }

    /**
     * 存储cookie
     */
    public function save_cookie($data, $remember = 0) {

        // 存储cookie
        $expire = $remember ? 8640000 : SITE_LOGIN_TIME;
        \Phpcmf\Service::L('Input')->set_cookie('member_uid', $data['id'], $expire);
        \Phpcmf\Service::L('Input')->set_cookie('member_cookie', substr(md5(SYS_KEY.$data['password']), 5, 20), $expire);

    }
    
    public function get_sso_url() {
        
        $url = [
            '/'
        ];

        return $url;
    }

    /**
     * sso 登录url
     */
    public function sso($data, $remember = 0) {

        $sso = [];
        // 同步登录地址

        $url = $this->get_sso_url();
        foreach ($url as $u) {
            $code = dr_authcode($data['id'].'-'.$data['salt'], 'ENCODE');
            $sso[]= $u.'api/sso.php?action=login&remember='.$remember.'&code='.$code;
        }

        return $sso;
    }

    /**
     * 前端会员退出登录
     */
    public function logout() {

        // 注销授权登陆的会员
        if (\Phpcmf\Service::C()->session()->get('member_auth_uid')) {
            \Phpcmf\Service::C()->session()->delete('member_auth_uid');
            return;
        }

        \Phpcmf\Service::L('Input')->set_cookie('member_uid', 0, -100000000);
        \Phpcmf\Service::L('Input')->set_cookie('member_cookie', '', -100000000);

        $sso = [];

        $url = $this->get_sso_url();
        foreach ($url as $u) {
            $sso[]= $u.'api/sso.php?action=logout';
        }

        return $sso;
    }

    // 查询会员信息
    private function _find_member_info($username) {

        $data = $this->db->table('member')->where('username', $username)->get()->getRowArray();
        if (!$data && \Phpcmf\Service::C()->member_cache['login']['field']) {
            if (in_array('email', \Phpcmf\Service::C()->member_cache['login']['field'])
                && \Phpcmf\Service::L('Form')->check_email($username)) {
                $data = $this->db->table('member')->where('email', $username)->get()->getRowArray();
            } elseif (in_array('phone', \Phpcmf\Service::C()->member_cache['login']['field'])
                && \Phpcmf\Service::L('Form')->check_phone($username)) {
                $data = $this->db->table('member')->where('phone', $username)->get()->getRowArray();
                if (!$data) {
                    return [];
                }
            }
        }

        $data['uid'] = $data['id'];

        return $data;
    }

    // 验证管理员登录权限
    private function _is_admin_login_member($uid) {



        return dr_return_data(1, 'ok');
    }

    /**
     * 验证登录
     *
     * @param	string	$username	用户名
     * @param	string	$password	明文密码
     * @param	intval	$remember	是否记住密码
     */
    public function login($username, $password, $remember = 0) {

        $data = $this->_find_member_info($username);
        if (!$data) {
            return dr_return_data(0, dr_lang('用户不存在'));
        }
        // 密码验证
        $password = dr_safe_password($password);
        if (md5(md5($password).$data['salt'].md5($password)) != $data['password']) {
            return dr_return_data(0, dr_lang('密码不正确'));
        }

        // 验证管理员登录
        $rt = $this->_is_admin_login_member($data['id']);
        if (!$rt['code']) {
            return $rt;
        }

        // 保存本地会话
        $this->save_cookie($data, $remember);

        // 记录日志
        $this->_login_log($data);

        return dr_return_data(1, 'ok', ['member' => $data, 'sso' => $this->sso($data, $remember)]);
    }
    
    // 授权登录
    public function login_oauth($name, $data) {
        

    }
    
    // 绑定注册模式 授权注册绑定
    public function register_oauth_bang($oauth, $groupid, $data) {



    }
    
    // 直接登录模式 授权注册
    public function register_oauth($groupid, $oauth) {


    }

    /**
     * 用户注册
     *
     * @param   用户组
     * @param	注册账户信息
     * @param	自定义字段信息
     * @param	是否注册到服务器
     */
    public function register($groupid, $member, $data = [], $sync = 1) {
        
        $member['email'] && $member['email'] = strtolower($member['email']);
        $member['username'] && $member['username'] = strtolower($member['username']);

        // 验证唯一性
        if ($member['username'] && $this->db->table('member')->where('username', $member['username'])->countAllResults()) {
            return dr_return_data(0, dr_lang('账号%s已经注册', $member['username']), ['field' => 'username']);
        } elseif ($member['email'] && $this->db->table('member')->where('email', $member['email'])->countAllResults()) {
            return dr_return_data(0, dr_lang('邮箱%s已经注册', $member['email']), ['field' => 'email']);
        } elseif ($member['phone'] && $this->db->table('member')->where('phone', $member['phone'])->countAllResults()) {
            return dr_return_data(0, dr_lang('手机号码%s已经注册', $member['phone']), ['field' => 'phone']);
        }

        $ucsso_id = 0;


        // 默认登录账号
        !$member['username'] && $member['username'] = $member['phone'];
        !$member['username'] && $member['username'] = $member['email'];
        !$member['name'] && $member['name'] = '';
        $member['salt'] = substr(md5(rand(0, 999)), 0, 10); // 随机10位密码加密码
        $member['password'] = $member['password'] ? md5(md5($member['password']).$member['salt'].md5($member['password'])) : '';
        $member['money'] = 0;
        $member['freeze'] = 0;
        $member['spend'] = 0;
        $member['score'] = 0;
        $member['experience'] = 0;
        $member['regip'] = (string)\Phpcmf\Service::L('Input')->ip_address();
        $member['regtime'] = SYS_TIME;
        $member['randcode'] = rand(100000, 999999);
        $rt = $this->table('member')->insert($member);
        if (!$rt['code']) {
            return dr_return_data(0, $rt['msg']);
        }

        // 附表信息
        $data['id'] = $member['uid'] = $uid = $rt['code'];
        $data['is_lock'] = 0;
        $data['is_auth'] = 0;
        $data['is_admin'] = 0;
        $data['is_avatar'] = 0;
        // 审核状态值
        $data['is_verify'] = IS_ADMIN ? 1 : (\Phpcmf\Service::C()->member_cache['register']['verify'] ? 0 : 1);
        $data['is_mobile'] = 0;
        $data['is_complete'] = 0;
        $rt = $this->table('member_data')->insert($data);
        if (!$rt['code']) {
            // 删除主表
            $this->table('member')->delete($uid);
            return dr_return_data(0, $rt['msg']);
        }

        // uid 同步
        if ($ucsso_id && defined('UCSSO_API')) {
            $rt = ucsso_syncuid($ucsso_id, $uid);
            if (!$rt['code']) {
                // 同步失败
                log_message('error', 'UCSSO同步uid失败：'.$rt['msg']);
            }
        }

        // 归属用户组

        $data = $member + $data;



        // 注册后的通知
        \Phpcmf\Service::L('Notice')->send_notice('member_register', $data);

        // 注册后的钩子
        \Phpcmf\Hooks::trigger('member_register_after', $data);

        return dr_return_data(1, 'ok', $data);
    }

    /**
     * 存储授权信息
     */
    public function insert_oauth($uid, $type, $data, $state = '') {

        }

    // 修改密码 
    public function edit_password($member, $password) {

        $id = (int)$member['id'];
        $password = dr_safe_password($password);
        if (!$id || !$password) {
            return false;
        }

        if (defined('UCSSO_API')) {
            $rt = ucsso_edit_password($id, $password);
            // 修改失败
            if (!$rt['code']) {
                return false;
            }
        }

        $update['salt'] = substr(md5(rand(0, 999)), 0, 10); // 随机10位密码加密码
        $update['randcode'] = 0;
        $update['password'] = md5(md5($password).$update['salt'].md5($password));
        $this->db->table('member')->where('id', $id)->update($update);

        $member['uid'] = $id;

        return true;
    }

    /**
     * 邮件发送
     */
    public function sendmail($tomail, $subject, $msg, $data = []) {



        return dr_return_data(0, 'Error');
    }

    /**
     * 短信发送验证码
     */
    public function sendsms_code($mobile, $code) {

        return $this->sendsms_text($mobile, $code, 'code');
    }

    /**
     * 短信发送文本
     */
    public function sendsms_text($mobile, $content, $type = 'text') {


        return dr_return_data(0, dr_lang('接口配置文件不存在'));
    }

    /**
     * 增加金币
     *
     * @param	intval	$uid	会员id
     * @param	intval	$value	分数变动值
     * @param	string	$mark	标记
     * @param	string	$note	备注
     * @param	intval	$count	统计次数
     * @return	intval
     */
    public function add_score($uid, $val, $note = '', $url = '', $mark = '', $count = 0) {


    }

    /**
     * 获取微信 access token
     */
    public function _weixin_template_access_token() {


    }

    /**
     * 发送微信通知模板
     *
     * $uid	会员id
     * $id 	微信模板id
     * $data	通知内容
     * $url	详细地址
     * $color	top颜色
     */
    public function wexin_template($uid, $id, $data, $url = '', $color = '') {


    }

    /**
     * 增加经验
     *
     * @param	intval	$uid	会员id
     * @param	intval	$value	分数变动值
     * @param	string	$mark	标记
     * @param	string	$note	备注
     * @param	intval	$count	统计次数
     * @return	intval
     */
    public function add_experience($uid, $val, $note = '', $url = '', $mark = '', $count = 0) {


    }

    // 增加money
    public function add_money($uid, $value) {


    }

    // 冻结资金
    public function add_freeze($uid, $value) {


    }

    // 取消冻结资金
    public function cancel_freeze($uid, $value) {


    }

    // 用户系统缓存
    public function cache() {

        $cache = [];

        // 获取会员全部配置信息
        $result = $this->db->table('member_setting')->get()->getResultArray();
        if ($result) {
            foreach ($result as $t) {
                $cache[$t['name']] = dr_string2array($t['value']);
            }
        }

        // 字段归属
        $cache['myfield'] = $cache['field'];

        // 自定义字段
        $register_field = $group_field = $cache['field'] = [];
        $field = $this->db->table('field')->where('disabled', 0)->where('relatedname', 'member')->orderBy('displayorder ASC,id ASC')->get()->getResultArray();
        if ($field) {
            foreach ($field as $f) {
                $f['setting'] = dr_string2array($f['setting']);
                $cache['field'][$f['fieldname']] = $f;
                // 归类用户组字段
                if ($cache['myfield'][$f['id']]) {
                    foreach ($cache['myfield'][$f['id']] as $gid) {
                        $group_field[$gid][] = $f['fieldname'];
                    }
                }
                // 归类可用注册的字段
                if ($cache['register_field'][$f['id']]) {
                    $register_field[] = $f['fieldname'];
                }
            }
        }


        // 支付接口
        if ($cache['payapi']) {
            foreach ($cache['payapi'] as $i => $t) {
                if (!$t['use']) {
                    unset($cache['payapi'][$i]);
                }
            }
        }

        // 注册配置
        $cache['register']['notallow'] = explode(',', $cache['register']['notallow']);

        // 用户组权限id
        $cache['authid'] = [ 0 ];

        // 用户组
        $cache['register']['group'] = $cache['group'] = [];
        $group = $this->db->table('member_group')->orderBy('displayorder ASC,id ASC')->get()->getResultArray();
        if ($group) {
            foreach ($group as $t) {
                $level = $this->db->table('member_level')->where('gid', $t['id'])->orderBy('value ASC,id ASC')->get()->getResultArray();
                if ($level) {
                    foreach ($level as $lv) {
                        $cache['authid'][] = $t['id'].'-'.$lv['id'];
                        $t['level'][$lv['id']] = $lv;
                    }
                } else {
                    $cache['authid'][] = $t['id'];
                }
                $t['setting'] = dr_string2array($t['setting']);
                // 用户组的可用字段
                $t['field'] = $group_field[$t['id']];
                // 当前用户组开启了注册时, 查询它可注册的字段
                $t['register'] && $t['field'] && $t['register_field'] = $register_field ? array_intersect($t['field'], $register_field) : [];
                // 是否允许注册
                $t['register'] && $cache['register']['group'][] = $t['id'];
                $cache['group'][$t['id']] = $t;
            }
        }




        \Phpcmf\Service::L('cache')->set_file('member', $cache);
    }
}